package org.example.controller;

import org.example.service.WebSocketServer;
import org.example.utils.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;


/**
 * @description: <br>
 * @date: 2022/3/18 17:01 <br>
 * @author: ichpeng@hotmail.com <br>
 * @version: 1.0 <br>
 */
@RequestMapping("/")
@Controller
public class IndexController {

    Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    WebSocketServer socketServer;

    @RequestMapping("")
    public String index(){
        return "websocket";
    }

    @ResponseBody
    @RequestMapping("/send/{id}/{message}")
    public String send(@PathVariable String id, @PathVariable String message){
        try {
            socketServer.sendToUser(new Exception(message).toString(), id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return String.format("send to client %s, message is [%s] ok.", id, message);
    }

    @RequestMapping("logger")
    public String logger(){
        return "logWebSocket";
    }
    @ResponseBody
    @RequestMapping("/logger/{level}/{message}")
    public String sendLogger(@PathVariable String level, @PathVariable String message){
        try {
            System.out.println(1/0);
        } catch (Exception e) {
//            LogUtil.error(logger, "测试", e);
            if(LogUtil.LEVEL.ERROR.getDesc().equals(level)){
                LogUtil.error(logger, message, e);
            }else if(LogUtil.LEVEL.WARN.getDesc().equals(level)){
                LogUtil.warn(logger, message, e);
            }else if(LogUtil.LEVEL.INFO.getDesc().equals(level)){
                LogUtil.info(logger, message, e);
            }else if(LogUtil.LEVEL.DEBUG.getDesc().equals(level)){
                LogUtil.debug(logger, message, e);
            }else if(LogUtil.LEVEL.TRACE.getDesc().equals(level)){
                LogUtil.trace(logger, message, e);
            }else {
                LogUtil.info(logger, message, e);
            }
            e.printStackTrace();
        }
        return String.format("send logger to client %s, message is [%s] ok.", level, message);
    }


}
